package cn.bon.websocket;

import cn.bon.websocket.handler.DefaultWebsocketStartSuccessHandler;
import cn.bon.websocket.handler.WebsocketServerInitializerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;

/**
 * @author: dronff
 * @description:
 * @CreateTime: 2023/12/9 20:32
 **/

@Configuration
@Data
@ConfigurationProperties(prefix = "websocket")
@Slf4j
@MapperScan("cn.bon.websocket.mapper")
@ComponentScan("cn.bon.websocket")
public class WebsocketApplication {
    private String serviceName = "websocket";
    @Resource
    private WebsocketServerInitializerHandler websocketServerInitializerHandler;
    private int port = 8890;
    public void startService(){

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(8);
        try {
            log.info("正在启动websocket服务，正在监听端口:" + port);
            new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(
                            websocketServerInitializerHandler
                    )
                    .bind(port)
                    .addListener(new DefaultWebsocketStartSuccessHandler(bossGroup, workerGroup));
        } finally {

        }
    }

    @PostConstruct
    @Async
    public void postConstructor(){
        this.startService();
    }
}
